﻿Imports ATS.HelperClass
Imports ATS.EntryValidation
Imports Microsoft.Windows.Controls

Partial Public Class ucItems2
    Dim lastActionBy As String = "gencpros"
    Dim dbItems As ATSDataClassesDataContext = New ATSDataClassesDataContext
    Private _pageIsValid As Boolean = True
    Dim editFlag As Integer
    Dim al As New ArrayList
    Dim ofdImage As New System.Windows.Forms.OpenFileDialog



    Sub pageIsValid(ByVal sender As String, ByVal isValid As Boolean)

        Dim inArray As Boolean = False
        For i = 0 To al.Count - 1
            If al.Item(i) = sender Then
                If isValid Then
                    al.Remove(Trim(sender))
                End If
                inArray = True
                Exit For
            End If
        Next
        If Not inArray Then
            If Not isValid Then
                al.Add(Trim(sender))
            End If
        End If
        If al.Count > 0 Then
            _pageIsValid = False
        Else
            _pageIsValid = True
        End If
    End Sub

    Private Sub ucItems2_Initialized(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Initialized
        Try

        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
    End Sub

    Private Sub ucItems_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        Try

        
        LoadItems()
        LoadCategory()
        LoadLocations()
        LoadDepartments()
        LoadPersons()
        LoadDisposalType()

        editFlag = HelperClass.EditMode.Load
            DisableAllControls()
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
    End Sub

    Private Sub LoadItems(Optional ByVal itemFilter As String = "")
        Dim itemTable = From itemDetails In dbItems.MainAssetsTables _
                        Where itemDetails.Assetno.Contains(itemFilter) _
                        Group Join leaseDetails In dbItems.LeasedAssets _
                        On itemDetails.Assetno Equals leaseDetails.AssetNo _
                        Into RightTableResults = Group _
                        From leaseDetails In RightTableResults.DefaultIfEmpty _
                        Group Join warrantyDetails In dbItems.Warranties _
                        On itemDetails.Assetno Equals warrantyDetails.AssetNo _
                        Into RightTableResultsWarranty = Group _
                        From warrantyDetails In RightTableResultsWarranty.DefaultIfEmpty _
                        Group Join disposeDetails In dbItems.DisposedAssets _
                        On itemDetails.Assetno Equals disposeDetails.Assetno _
                        Into RightTableResultsDisposed = Group _
                        From disposeDetails In RightTableResultsDisposed.DefaultIfEmpty _
                        Select itemDetails, leaseDetails, warrantyDetails, disposeDetails _
                        , AssetNumber = itemDetails.Assetno _
                        , CategoryDisplay = itemDetails.Category.CategoryName

        'Order By itemDetails.CategoryCode, itemDetails.Assetno _
        'Select itemDetails, leaseDetails _
        ', AssetNumber = itemDetails.Assetno _
        ', CategoryDisplay = itemDetails.Category

        listBoxItems.DataContext = itemTable
        listBoxItems.SelectedIndex = 0

        If itemTable.Count > 0 Then
            loadfields(itemTable)

            ucActions.buttonEditMain.IsEnabled = True
            ucActions.buttonDeleteMain.IsEnabled = True
        Else
            ClearAllControls()
            ucActions.buttonEditMain.IsEnabled = False
            ucActions.buttonDeleteMain.IsEnabled = False
        End If
        If itemTable.Count = 1 Then
            ExpanderText.Text = itemTable.Count & " record found"
        Else
            ExpanderText.Text = itemTable.Count & " records found"
        End If
    End Sub
    Sub loadfields(ByVal itemDetails As IQueryable)
        Dim xy = From dx In itemDetails
        With xy.First
            textboxDescription.Text = .itemDetails.DescriptiveName
            comboboxCategory.SelectedValue = .itemDetails.CategoryCode
            comboboxLocation.SelectedValue = .itemDetails.LocationCode
            comboboxDepartment.SelectedValue = .itemDetails.DeptCode
            textboxSection.Text = .itemDetails.Section
            comboboxPerson.SelectedValue = .itemDetails.AssignToEmployeeCode
            textboxReplacementCost.Text = FormatNumber(.itemDetails.ReplacementCost, 2)
            textboxCondition.Text = .itemDetails.Condition
            textboxStatus.Text = .itemDetails.Status
            textboxSerialNumber.Text = .itemDetails.SerialNumber

            textboxRemarks.Text = .itemDetails.Remarks

            textboxAssetNumber.Text = .itemDetails.Assetno
            textboxRFIDNumber.Text = .itemDetails.RFIDno
            textboxInvoiceNumber.Text = .itemDetails.InvoiceNumber
            If .itemDetails.DateAcquired Is Nothing Then
                cbCalendar.IsChecked = False
                textboxPurchasedDate.SelectedDate = Nothing
            Else
                cbCalendar.IsChecked = True
                textboxPurchasedDate.SelectedDate = .itemDetails.DateAcquired
            End If
            textboxBoughtFrom.Text = .itemDetails.BoughtFrom
            textboxBaseCost.Text = FormatNumber(.itemDetails.BaseCost, 2)
            If .itemdetails.salvagevalue Is Nothing Then
                .itemdetails.salvagevalue = 0
            End If
            textboxSalvageValue.Text = FormatNumber(.itemdetails.salvagevalue, 2)
            textboxVAT.Text = FormatNumber(.itemDetails.VAT, 2)
            textboxManufacturer.Text = .itemDetails.Manufacturer
            textboxBrand.Text = .itemDetails.BrandName
            textboxModelNumber.Text = .itemDetails.ModelNumber
            If CInt(.itemdetails.assetamount) > 0 Then
                textboxTotalCost.Text = FormatNumber(.itemDetails.AssetAmount, 2)
            Else
                textboxTotalCost.Text = FormatNumber(CInt(textboxBaseCost.Text) + CInt(textboxVAT.Text), 2)
            End If


            If Not .leaseDetails Is Nothing Then
                checkboxLeaseAsset.IsChecked = True
                If Not .leaseDetails.LeaseBegin Is Nothing Then
                    textboxLeaseStart.SelectedDate = .leaseDetails.LeaseBegin
                    cbCalendarLeaseStart.IsChecked = True
                Else

                    textboxLeaseStart.SelectedDate = Nothing
                    cbCalendarLeaseStart.IsChecked = False
                End If
                textboxWarrantyDetails.Text = .leaseDetails.LeaseDescription
            Else
                checkboxLeaseAsset.IsChecked = False

                textboxLeaseStart.SelectedDate = Nothing
                cbCalendarLeaseStart.IsChecked = False
                textboxWarrantyDetails.Text = Nothing
            End If

            If Not .warrantyDetails Is Nothing Then
                checkboxWarranty.IsChecked = True
                If Not .warrantydetails.warrantyExpiration Is Nothing Then
                    textboxWarrantyEnd.SelectedDate = .warrantydetails.warrantyExpiration
                    cbCalendarWarrantyEnd.IsChecked = True
                Else

                    textboxWarrantyEnd.SelectedDate = Nothing
                    cbCalendarWarrantyEnd.IsChecked = False
                End If
                textboxWarrantyDetails.Text = .warrantydetails.WarrantyType
            Else
                cbCalendarWarrantyEnd.IsChecked = False

                textboxWarrantyEnd.SelectedDate = Nothing
                textboxWarrantyDetails.Text = Nothing
            End If

            If Not .disposeDetails Is Nothing Then
                checkBoxDisposedAsset.IsChecked = True
                If Not .disposeDetails.datesold Is Nothing Then
                    textboxDateDisposed.SelectedDate = .disposeDetails.dateSold
                    cbCalendarDateDisposed.IsChecked = True
                Else
                    textboxDateDisposed.SelectedDate = Nothing
                    cbCalendarDateDisposed.IsChecked = False
                End If
                comboboxDisposalType.SelectedValue = .disposeDetails.DisposalMethod
            Else
                checkBoxDisposedAsset.IsChecked = False
                textboxDateDisposed.SelectedDate = Nothing
                comboboxDisposalType.SelectedValue = Nothing
                textboxSalvageValue.Text = FormatNumber("0", 2)
                textboxAmountSold.Text = FormatNumber("0", 2)
                textboxAccumulatedDepreciation.Text = FormatNumber("0", 2)
                textboxBV.Text = FormatNumber("0", 2)
                textboxGainLoss.Text = FormatNumber("0", 2)
                textboxProfit.Text = FormatNumber("0", 2)
                cbCalendarDateDisposed.IsChecked = False
            End If

            loadimages()


        End With
        pageIsValid(textboxDescription.Name, EntryValidation.ValidateText(textboxDescription))
        pageIsValid(comboboxCategory.Name, EntryValidation.ValidateCombo(comboboxCategory))
        pageIsValid(textboxAssetNumber.Name, EntryValidation.ValidateText(textboxAssetNumber))
    End Sub

    Private Sub LoadSelectedItems(Optional ByVal itemFilter As String = "")
        Dim itemTable = From itemDetails In dbItems.MainAssetsTables _
                        Where itemDetails.Assetno.Contains(itemFilter) _
                        Group Join leaseDetails In dbItems.LeasedAssets _
                        On itemDetails.Assetno Equals leaseDetails.AssetNo _
                        Into RightTableResults = Group _
                        From leaseDetails In RightTableResults.DefaultIfEmpty _
                        Group Join warrantyDetails In dbItems.Warranties _
                        On itemDetails.Assetno Equals warrantyDetails.AssetNo _
                        Into RightTableResultsWarranty = Group _
                        From warrantyDetails In RightTableResultsWarranty.DefaultIfEmpty _
                        Group Join disposeDetails In dbItems.DisposedAssets _
                        On itemDetails.Assetno Equals disposeDetails.Assetno _
                        Into RightTableResultsDisposed = Group _
                        From disposeDetails In RightTableResultsDisposed.DefaultIfEmpty _
                        Select itemDetails, leaseDetails, warrantyDetails, disposeDetails _
                        , AssetNumber = itemDetails.Assetno _
                        , CategoryDisplay = itemDetails.Category.CategoryName



        'Order By itemDetails.CategoryCode, itemDetails.Assetno _
        'Select itemDetails, leaseDetails _
        ', AssetNumber = itemDetails.Assetno _
        ', CategoryDisplay = itemDetails.Category

        'listBoxItems.DataContext = itemTable
        'listBoxItems.SelectedIndex = 0

        If itemTable.Count > 0 Then
            loadfields(itemTable)
            ucActions.buttonEditMain.IsEnabled = True
            ucActions.buttonDeleteMain.IsEnabled = True
        Else
            ClearAllControls()
            ucActions.buttonEditMain.IsEnabled = False
            ucActions.buttonDeleteMain.IsEnabled = False
        End If
        'If itemTable.Count = 1 Then
        '    ExpanderText.Text = itemTable.Count & " record found"
        'Else
        '    ExpanderText.Text = itemTable.Count & " records found"
        'End If
    End Sub

    Private Sub listBoxItems_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles ListBoxItemImages.SelectionChanged
        Dim selectedItem As String = ""
        If Not listBoxItems.SelectedItem Is Nothing Then
            selectedItem = listBoxItems.SelectedValue.itemDetails.Assetno.ToString
        End If
        LoadSelectedItems(selectedItem)
    End Sub

    Private Sub LoadCategory()
        Dim categoryTable = From categoryDetails In dbItems.Categories _
                            Order By categoryDetails.CategoryName

        comboboxCategory.ItemsSource = categoryTable
        comboboxCategory.SelectedIndex = 0
        comboboxCategory.SelectedValuePath = "CategoryCode"
        comboboxCategory.DisplayMemberPath = "CategoryName"
    End Sub

    Private Sub LoadLocations()
        Dim locationsTable = From locationDetails In dbItems.Locations _
                            Order By locationDetails.LocationName

        comboboxLocation.ItemsSource = locationsTable
        comboboxLocation.SelectedIndex = 0
        comboboxLocation.SelectedValuePath = "LocationCode"
        comboboxLocation.DisplayMemberPath = "LocationName"
    End Sub

    Private Sub LoadDisposalType()
        Dim disposalTable = From disposalDetails In dbItems.DisposedAssets _
                            Order By disposalDetails.DisposalMethod

        comboboxDisposalType.ItemsSource = disposalTable
        comboboxDisposalType.SelectedIndex = 0
        comboboxDisposalType.SelectedValuePath = "DisposalMethod"
        comboboxDisposalType.DisplayMemberPath = "DisposalMethod"


    End Sub

    Private Sub LoadDepartments()
        Dim departmentTable = From departmentList In dbItems.Departments _
                               Order By departmentList.DepartmentName

        comboboxDepartment.ItemsSource = departmentTable
        comboboxDepartment.SelectedValuePath = "DepartmentCode"
        comboboxDepartment.DisplayMemberPath = "DepartmentName"
    End Sub

    Private Sub LoadPersons()
        Dim personTable = From personList In dbItems.Persons _
                          Order By personList.LastName & ", " & personList.FirstName.ToUpper _
                          Select personList.EmployeeID _
                          , personName = Trim(personList.LastName & IIf(personList.LastName.Length > 0 And personList.FirstName.Length > 0, ", ", " ") & personList.FirstName.ToUpper)
        comboboxPerson.ItemsSource = personTable
        comboboxPerson.SelectedValuePath = "EmployeeID"
        comboboxPerson.DisplayMemberPath = "personName"

    End Sub

    Private Sub ucActions_AddButtonClicked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ucActions.AddButtonClicked
        gridListbox.IsEnabled = False
        editFlag = EditMode.Add
        ClearAllControls()
        EnableAllControls()
    End Sub

    Private Sub ucActions_CancelButtonClicked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ucActions.CancelButtonClicked
        Dim selectedItem As String = ""
        If Not listBoxItems.SelectedValue Is Nothing Then
            selectedItem = listBoxItems.SelectedValue.itemDetails.Assetno.ToString
        End If

        editFlag = EditMode.Load
        DisableAllControls()
        LoadSelectedItems(selectedItem)
        gridListbox.IsEnabled = True

    End Sub

    Private Sub ucActions_DeleteButtonClicked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ucActions.DeleteButtonClicked
        Try
            Dim warningString As String = "Do you really want to delete this record?" & ControlChars.Lf & ControlChars.Lf & listBoxItems.SelectedItem.AssetNumber.ToString
            If System.Windows.MessageBox.Show(warningString, "Delete Record", MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                Dim selectedItemCode As String = listBoxItems.SelectedValue.itemDetails.Assetno.ToString
                Dim itemsTable = From itemDetails In dbItems.MainAssetsTables _
                             Where itemDetails.Assetno.ToUpper = (selectedItemCode.ToUpper)
                dbItems.MainAssetsTables.DeleteOnSubmit(itemsTable.First)
                dbItems.SubmitChanges()
                LoadItems()
            End If
        Catch ex As Exception
            CheckForSQLErrors(ex)
        End Try
    End Sub

    Private Sub ucActions_EditButtonClicked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ucActions.EditButtonClicked
        editFlag = EditMode.Edit
        gridListbox.IsEnabled = False
        EnableAllControls()
        textboxAssetNumber.IsEnabled = False
    End Sub

    Private Sub ucActions_SaveButtonClicked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ucActions.SaveButtonClicked
        Try
            If _pageIsValid Then
                Dim ListBoxSelectedItemIndex As Integer = listBoxItems.SelectedIndex

                'Dim categoryTable = From categoryDetails In dbItems.Categories.Where(Function(p) p.CategoryName = comboboxCategory.Text)
                'If categoryTable.Count = 0 Then
                '    Dim categoryDetails As New Category
                '    With categoryDetails
                '        .CategoryName = comboboxCategory.Text
                '        .CategoryCode = comboboxCategory.Text
                '    End With
                '    dbItems.Categories.InsertOnSubmit(categoryDetails)
                'End If

                Dim locationTable = From locationDetails In dbItems.Locations.Where(Function(p) p.LocationName = comboboxLocation.Text)
                If locationTable.Count = 0 Then
                    Dim locationDetails As New Location
                    With locationDetails
                        .LocationName = comboboxLocation.Text
                        .LocationCode = comboboxLocation.Text
                    End With
                    dbItems.Locations.InsertOnSubmit(locationDetails)
                    LoadLocations()
                Else
                    If comboboxLocation.Text = "" Then
                        comboboxLocation.SelectedValue = ""
                    End If
                End If

                Dim departmentTable = From departmentDetails In dbItems.Departments.Where(Function(p) p.DepartmentName = comboboxDepartment.Text)
                If departmentTable.Count = 0 Then
                    Dim departmentDetails As New Department
                    With departmentDetails
                        .DepartmentName = comboboxDepartment.Text
                        .DepartmentCode = comboboxDepartment.Text
                    End With
                    dbItems.Departments.InsertOnSubmit(departmentDetails)
                    LoadDepartments()
                Else
                    If comboboxDepartment.Text = "" Then
                        comboboxDepartment.SelectedValue = ""
                    End If
                End If

                If editFlag = EditMode.Edit Then
                    Dim itemsTable = From itemDetails In dbItems.MainAssetsTables _
                                 Where itemDetails.Assetno = textboxAssetNumber.Text.ToUpper

                    With itemsTable.First
                        .DescriptiveName = textboxDescription.Text
                        .CategoryCode = comboboxCategory.SelectedValue
                        .LocationCode = comboboxLocation.SelectedValue
                        .DeptCode = comboboxDepartment.SelectedValue
                        .Section = textboxSection.Text
                        .AssignToEmployeeCode = comboboxPerson.SelectedValue
                        .ReplacementCost = textboxReplacementCost.Text
                        .Condition = textboxCondition.Text
                        .Status = textboxStatus.Text
                        .SerialNumber = textboxSerialNumber.Text

                        .Remarks = textboxRemarks.Text

                        .RFIDno = textboxRFIDNumber.Text
                        .InvoiceNumber = textboxInvoiceNumber.Text

                        If cbCalendar.IsChecked Then
                            .DateAcquired = textboxPurchasedDate.SelectedDate
                        Else
                            .DateAcquired = Nothing
                        End If
                        .SalvageValue = textboxSalvageValue.Text
                        .BoughtFrom = textboxBoughtFrom.Text
                        .BaseCost = textboxBaseCost.Text
                        .VAT = textboxVAT.Text
                        .AssetAmount = textboxTotalCost.Text
                        .Manufacturer = textboxManufacturer.Text
                        .BrandName = textboxBrand.Text
                        .ModelNumber = textboxModelNumber.Text

                        .LastModifiedBy = lastActionBy
                        .LastModified = Now
                    End With

                ElseIf editFlag = EditMode.Add Then
                    Dim saveNewItem As New MainAssetsTable
                    With saveNewItem
                        .Assetno = textboxAssetNumber.Text

                        .DescriptiveName = textboxDescription.Text
                        .CategoryCode = comboboxCategory.SelectedValue
                        .LocationCode = comboboxLocation.SelectedValue
                        .DeptCode = comboboxDepartment.SelectedValue
                        .Section = textboxSection.Text
                        .AssignToEmployeeCode = comboboxPerson.SelectedValue
                        .ReplacementCost = textboxReplacementCost.Text
                        .Condition = textboxCondition.Text
                        .Status = textboxStatus.Text
                        .SerialNumber = textboxSerialNumber.Text

                        .Remarks = textboxRemarks.Text

                        .RFIDno = textboxRFIDNumber.Text
                        .InvoiceNumber = textboxInvoiceNumber.Text

                        If cbCalendar.IsChecked Then
                            .DateAcquired = textboxPurchasedDate.SelectedDate
                        Else
                            .DateAcquired = Nothing
                        End If
                        .SalvageValue = textboxSalvageValue.Text
                        .BoughtFrom = textboxBoughtFrom.Text
                        .BaseCost = textboxBaseCost.Text
                        .VAT = textboxVAT.Text
                        .AssetAmount = textboxTotalCost.Text
                        .Manufacturer = textboxManufacturer.Text
                        .BrandName = textboxBrand.Text
                        .ModelNumber = textboxModelNumber.Text

                        .Createdby = lastActionBy
                        .DateCreated = Now
                    End With
                    dbItems.MainAssetsTables.InsertOnSubmit(saveNewItem)
                End If
                dbItems.SubmitChanges()

                Dim leasedTable = From leasedDetails In dbItems.LeasedAssets.Where(Function(p) p.AssetNo = textboxAssetNumber.Text)
                If checkboxLeaseAsset.IsChecked Then
                    If leasedTable.Count = 0 Then
                        Dim leasedDetails As New LeasedAsset
                        With leasedDetails
                            .LeaseBegin = evaluateDate(cbCalendarLeaseStart, textboxLeaseStart)
                            .LeaseEnd = evaluateDate(cbCalendarLeaseEnd, textboxLeaseEnd)
                            .AssetNo = textboxAssetNumber.Text
                            .LeaseDescription = textboxLeaseDetails.Text
                        End With
                        dbItems.LeasedAssets.InsertOnSubmit(leasedDetails)
                    Else
                        With leasedTable.First
                            .LeaseBegin = evaluateDate(cbCalendarLeaseStart, textboxLeaseStart)
                            .LeaseEnd = evaluateDate(cbCalendarLeaseEnd, textboxLeaseEnd)
                            .LeaseDescription = textboxLeaseDetails.Text
                        End With
                    End If
                Else
                    If Not leasedTable.Count = 0 Then
                        dbItems.LeasedAssets.DeleteOnSubmit(leasedTable.First)
                    End If
                End If


                Dim warrantyTable = From warrantyDetails In dbItems.Warranties.Where(Function(p) p.AssetNo = textboxAssetNumber.Text)
                If checkboxWarranty.IsChecked Then
                    If warrantyTable.Count = 0 Then
                        Dim warrantyDetails As New Warranty
                        With warrantyDetails
                            .AssetNo = textboxAssetNumber.Text
                            .WarrantyExpiration = evaluateDate(cbCalendarWarrantyEnd, textboxWarrantyEnd)
                            .WarrantyType = textboxWarrantyDetails.Text
                        End With
                        dbItems.Warranties.InsertOnSubmit(warrantyDetails)
                    Else
                        With warrantyTable.First
                            .WarrantyExpiration = evaluateDate(cbCalendarWarrantyEnd, textboxWarrantyEnd)
                            .WarrantyType = textboxWarrantyDetails.Text
                        End With
                    End If
                Else
                    If Not warrantyTable.Count = 0 Then
                        dbItems.Warranties.DeleteOnSubmit(warrantyTable.First)
                    End If
                End If

                Dim disposedTable = From disposedDetails In dbItems.DisposedAssets.Where(Function(p) p.Assetno = textboxAssetNumber.Text)
                If checkBoxDisposedAsset.IsChecked Then
                    If disposedTable.Count = 0 Then
                        Dim disposedDetails As New DisposedAsset
                        With disposedDetails
                            .Assetno = textboxAssetNumber.Text
                            .AmountSold = textboxAmountSold.Text
                            If cbCalendarDateDisposed.IsChecked Then
                                .DateSold = textboxDateDisposed.SelectedDate
                            Else
                                .DateSold = Nothing
                            End If
                            .DisposalAccmDepr = textboxAccumulatedDepreciation.Text
                            .DisposalBV = textboxBV.Text
                            .DisposalGainLoss = textboxGainLoss.Text
                            .DisposalMethod = comboboxDisposalType.Text
                            .Profit = textboxProfit.Text
                        End With
                        dbItems.DisposedAssets.InsertOnSubmit(disposedDetails)
                    Else
                        With disposedTable.First
                            .AmountSold = textboxAmountSold.Text
                            If cbCalendarDateDisposed.IsChecked Then
                                .DateSold = textboxDateDisposed.SelectedDate
                            Else
                                .DateSold = Nothing
                            End If
                            .DisposalAccmDepr = textboxAccumulatedDepreciation.Text
                            .DisposalBV = textboxBV.Text
                            .DisposalGainLoss = textboxGainLoss.Text
                            .DisposalMethod = comboboxDisposalType.Text
                            .Profit = textboxProfit.Text
                        End With
                    End If
                Else
                    If Not disposedTable.Count = 0 Then
                        dbItems.DisposedAssets.DeleteOnSubmit(disposedTable.First)
                    End If
                End If


                dbItems.SubmitChanges()
                'LoadItems()

                If searchBox.Text.Length > 0 Then
                    LoadItems(searchBox.Text)
                Else
                    If editFlag = EditMode.Add Then
                        LoadItems(textboxAssetNumber.Text)
                        searchBox.Text = textboxAssetNumber.Text
                    Else
                        LoadItems()
                    End If

                End If
                editFlag = EditMode.Load

                listBoxItems.SelectedIndex = ListBoxSelectedItemIndex
                DisableAllControls()
                gridListbox.IsEnabled = True
                _pageIsValid = True
            Else
                ucActions.buttonSaveMain.IsEnabled = True
                ucActions.buttonEditMain.IsEnabled = False
                ucActions.buttonAddMain.IsEnabled = False
                ucActions.buttonDeleteMain.IsEnabled = False
                ucActions.buttonCancelMain.IsEnabled = True
                Dim warningString As String = "Some mandatory fields are missing."
                System.Windows.MessageBox.Show(warningString, "Missing entry", MessageBoxButton.OK, MessageBoxImage.Information)
            End If
        Catch ex As Exception
            CheckForSQLErrors(ex)
            ucActions.buttonSaveMain.IsEnabled = True
            ucActions.buttonEditMain.IsEnabled = False
            ucActions.buttonAddMain.IsEnabled = False
            ucActions.buttonDeleteMain.IsEnabled = False
            ucActions.buttonCancelMain.IsEnabled = True
        End Try
    End Sub

    Private Sub DisableAllControls()
        HelperClass.DisableTextBox(gridItemGeneral)
        HelperClass.DisablePasswordBox(gridItemGeneral)
        HelperClass.DisableCheckBox(gridItemGeneral)
        HelperClass.DisableComboBox(gridItemGeneral)
        HelperClass.DisableTextBox(gridItemAdditional)
        HelperClass.DisablePasswordBox(gridItemAdditional)
        HelperClass.DisableCheckBox(gridItemAdditional)
        HelperClass.DisableComboBox(gridItemAdditional)
        HelperClass.DisableGroupBox(gridItemAdditional)
        'HelperClass.DisableTextBox(gridItemImages)
        'HelperClass.DisablePasswordBox(gridItemImages)
        'HelperClass.DisableCheckBox(gridItemImages)
        'HelperClass.DisableComboBox(gridItemImages)
        btnAddImage.IsEnabled = False
    End Sub
    Private Sub EnableAllControls()
        HelperClass.EnableTextBox(gridItemGeneral)
        HelperClass.EnablePasswordBox(gridItemGeneral)
        HelperClass.EnableCheckBox(gridItemGeneral)
        HelperClass.EnableComboBox(gridItemGeneral)
        HelperClass.EnableTextBox(gridItemAdditional)
        HelperClass.EnablePasswordBox(gridItemAdditional)
        HelperClass.EnableCheckBox(gridItemAdditional)
        HelperClass.EnableComboBox(gridItemAdditional)
        HelperClass.EnableGroupBox(gridItemAdditional)
        'HelperClass.EnableTextBox(gridItemImages)
        'HelperClass.EnablePasswordBox(gridItemImages)
        'HelperClass.EnableCheckBox(gridItemImages)
        'HelperClass.EnableComboBox(gridItemImages)
        btnAddImage.IsEnabled = True
    End Sub
    Private Sub ClearAllControls()
        HelperClass.ClearTextBox(gridItemGeneral)
        HelperClass.ClearPasswordBox(gridItemGeneral)
        HelperClass.ClearCheckBox(gridItemGeneral)
        HelperClass.ClearComboBox(gridItemGeneral)

        HelperClass.ClearTextBox(gridItemAdditional)
        HelperClass.ClearPasswordBox(gridItemAdditional)
        HelperClass.ClearCheckBox(gridItemAdditional)
        HelperClass.ClearComboBox(gridItemAdditional)

        HelperClass.ClearTextBox(groupBoxLeasedAsset)
        HelperClass.ClearPasswordBox(groupBoxLeasedAsset)
        HelperClass.ClearCheckBox(groupBoxLeasedAsset)
        HelperClass.ClearComboBox(groupBoxLeasedAsset)

        HelperClass.ClearTextBox(groupBoxWarranty)
        HelperClass.ClearPasswordBox(groupBoxWarranty)
        HelperClass.ClearCheckBox(groupBoxWarranty)
        HelperClass.ClearComboBox(groupBoxWarranty)

        HelperClass.ClearTextBox(groupBoxDispose)
        HelperClass.ClearPasswordBox(groupBoxDispose)
        HelperClass.ClearCheckBox(groupBoxDispose)
        HelperClass.ClearComboBox(groupBoxDispose)

        'HelperClass.ClearTextBox(gridItemImages)
        'HelperClass.ClearPasswordBox(gridItemImages)
        'HelperClass.ClearCheckBox(gridItemImages)
        'HelperClass.ClearComboBox(gridItemImages)


        textboxReplacementCost.Text = FormatNumber("0", 2)
        textboxBaseCost.Text = FormatNumber("0", 2)
        textboxVAT.Text = FormatNumber("0", 2)
        textboxTotalCost.Text = FormatNumber("0", 2)

        textboxSalvageValue.Text = FormatNumber("0", 2)
        textboxAmountSold.Text = FormatNumber("0", 2)
        textboxAccumulatedDepreciation.Text = FormatNumber("0", 2)
        textboxBV.Text = FormatNumber("0", 2)
        textboxGainLoss.Text = FormatNumber("0", 2)
        textboxProfit.Text = FormatNumber("0", 2)
    End Sub


    Private Sub searchButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles searchButton.Click
        LoadItems(searchBox.Text)
    End Sub

    Private Sub searchBox_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles searchBox.TextChanged
        LoadItems(searchBox.Text)
    End Sub

    Private Sub textboxAssetNumber_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles textboxAssetNumber.TextChanged
        pageIsValid(sender.name, EntryValidation.ValidateText(sender))
        If editFlag = EditMode.Add Then
            Dim selectedItem As String = textboxAssetNumber.Text.ToString
            Dim itemTable = From itemDetails In dbItems.MainAssetsTables _
                         Where itemDetails.Assetno = selectedItem.ToUpper
            If itemTable.Count > 0 And textboxAssetNumber.IsEnabled = True Then
                _pageIsValid = False
                textboxAssetNumber.BorderBrush = New SolidColorBrush(Colors.Red)
                textboxAssetNumber.ToolTip = "Asset Number already exist."
            End If
        End If
    End Sub

    Private Sub textboxDescription_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles textboxDescription.TextChanged
        pageIsValid(sender.name, EntryValidation.ValidateText(sender))
    End Sub

    Private Sub comboboxCategory_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles comboboxCategory.SelectionChanged
        pageIsValid(sender.name, EntryValidation.ValidateCombo(sender))
    End Sub

    Private Sub cbCalendar_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles cbCalendar.Unchecked, cbCalendar.Checked
        checkboxDateProcess(cbCalendar, textboxPurchasedDate)
        'If cbCalendar.IsChecked And cbCalendar.IsEnabled Then
        '    textboxPurchasedDate.IsEnabled = True
        '    pageIsValid(textboxPurchasedDate.Name, EntryValidation.ValidateDatePicker(textboxPurchasedDate))
        'Else
        '    textboxPurchasedDate.ClearValue(ComboBox.BorderBrushProperty)
        '    pageIsValid(textboxPurchasedDate.Name, True)
        '    textboxPurchasedDate.IsEnabled = False
        'End If
    End Sub

    Private Sub cbCalendar_IsEnabledChanged(ByVal sender As Object, ByVal e As System.Windows.DependencyPropertyChangedEventArgs) Handles cbCalendar.IsEnabledChanged
        checkboxDateProcess(cbCalendar, textboxPurchasedDate)
        'If cbCalendar.IsChecked And cbCalendar.IsEnabled Then
        '    textboxPurchasedDate.IsEnabled = True
        '    pageIsValid(textboxPurchasedDate.Name, EntryValidation.ValidateDatePicker(textboxPurchasedDate))
        'Else
        '    textboxPurchasedDate.ClearValue(ComboBox.BorderBrushProperty)
        '    pageIsValid(textboxPurchasedDate.Name, True)
        '    textboxPurchasedDate.IsEnabled = False
        'End If
    End Sub

    Private Sub textboxPurchasedDate_SelectedDateChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles textboxPurchasedDate.SelectedDateChanged
        pageIsValid(sender.Name, EntryValidation.ValidateDatePicker(sender))
    End Sub

    Sub checkboxDateProcess(ByVal cbcalendarName As CheckBox, ByVal correspondingCalendar As DatePicker)
        If cbcalendarName.IsChecked And cbcalendarName.IsEnabled Then
            correspondingCalendar.IsEnabled = True
            pageIsValid(correspondingCalendar.Name, EntryValidation.ValidateDatePicker(correspondingCalendar))
        Else
            correspondingCalendar.ClearValue(ComboBox.BorderBrushProperty)
            pageIsValid(correspondingCalendar.Name, True)
            correspondingCalendar.IsEnabled = False
        End If
    End Sub

    Private Sub cbCalendarLeaseStart_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles cbCalendarLeaseStart.Checked, cbCalendarLeaseStart.Unchecked
        checkboxDateProcess(cbCalendarLeaseStart, textboxLeaseStart)
    End Sub
    Private Sub cbCalendarLeaseStart_IsEnabledChanged(ByVal sender As Object, ByVal e As System.Windows.DependencyPropertyChangedEventArgs) Handles cbCalendarLeaseStart.IsEnabledChanged
        checkboxDateProcess(cbCalendarLeaseStart, textboxLeaseStart)
    End Sub
    Private Sub textboxLeaseStart_SelectedDateChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles textboxLeaseStart.SelectedDateChanged
        pageIsValid(sender.Name, EntryValidation.ValidateDatePicker(sender))
    End Sub
    Private Sub cbCalendarLeaseEnd_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles cbCalendarLeaseEnd.Checked, cbCalendarLeaseEnd.Unchecked
        checkboxDateProcess(cbCalendarLeaseEnd, textboxLeaseEnd)
    End Sub
    Private Sub cbCalendarLeaseEnd_IsEnabledChanged(ByVal sender As Object, ByVal e As System.Windows.DependencyPropertyChangedEventArgs) Handles cbCalendarLeaseEnd.IsEnabledChanged
        checkboxDateProcess(cbCalendarLeaseEnd, textboxLeaseEnd)
    End Sub
    Private Sub textboxLeaseEnd_SelectedDateChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles textboxLeaseEnd.SelectedDateChanged
        pageIsValid(sender.Name, EntryValidation.ValidateDatePicker(sender))
    End Sub

    Private Sub cbCalendarWarrantyEnd_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles cbCalendarWarrantyEnd.Checked, cbCalendarWarrantyEnd.Unchecked
        checkboxDateProcess(cbCalendarWarrantyEnd, textboxWarrantyEnd)
    End Sub
    Private Sub cbCalendarWarrantyEnd_IsEnabledChanged(ByVal sender As Object, ByVal e As System.Windows.DependencyPropertyChangedEventArgs) Handles cbCalendarWarrantyEnd.IsEnabledChanged
        checkboxDateProcess(cbCalendarWarrantyEnd, textboxWarrantyEnd)
    End Sub
    Private Sub textboxWarrantyEnd_SelectedDateChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles textboxWarrantyEnd.SelectedDateChanged
        pageIsValid(sender.Name, EntryValidation.ValidateDatePicker(sender))
    End Sub

    Private Sub cbCalendarDateDisposed_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles cbCalendarDateDisposed.Checked, cbCalendarDateDisposed.Unchecked
        checkboxDateProcess(cbCalendarDateDisposed, textboxDateDisposed)
    End Sub

    Private Sub cbCalendarDateDisposed_IsEnabledChanged(ByVal sender As Object, ByVal e As System.Windows.DependencyPropertyChangedEventArgs) Handles cbCalendarDateDisposed.IsEnabledChanged
        checkboxDateProcess(cbCalendarDateDisposed, textboxDateDisposed)
    End Sub
    Private Sub textboxDateDisposed_SelectedDateChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles textboxDateDisposed.SelectedDateChanged
        pageIsValid(sender.Name, EntryValidation.ValidateDatePicker(sender))
    End Sub

    Function evaluateDate(ByVal cbCalendarName As CheckBox, ByVal correspondingCalendar As DatePicker) As Object
        If cbCalendarName.IsChecked Then
            evaluateDate = correspondingCalendar.SelectedDate
        Else
            evaluateDate = Nothing
        End If
        Return evaluateDate
    End Function

    Private Sub isNumeric_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles textboxSalvageValue.TextChanged, _
        textboxReplacementCost.TextChanged, _
        textboxBaseCost.TextChanged, _
        textboxVAT.TextChanged, _
        textboxTotalCost.TextChanged, _
        textboxAmountSold.TextChanged, _
        textboxProfit.TextChanged, _
        textboxGainLoss.TextChanged, _
        textboxAccumulatedDepreciation.TextChanged, _
        textboxBV.TextChanged

        pageIsValid(sender.Name, ValidateIsNumeric(sender))
    End Sub

    Private Sub buttonDeleteItemClickHandler(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
        If ucActions.cancelImage.IsEnabled = True Then
            Try
                Dim warningString As String = "Do you really want to delete this image?" & ControlChars.Lf & ListBoxItemImages.SelectedItem.ImageName.ToString
                If System.Windows.MessageBox.Show(warningString, "Delete Record", MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                    Dim imageCounter As Integer = ListBoxItemImages.SelectedItem.ImageCtr
                    Dim imageTable = From imageDetails In dbItems.akaImages _
                                 Where imageDetails.ImageCtr = imageCounter

                    dbItems.akaImages.DeleteOnSubmit(imageTable.First)
                    dbItems.SubmitChanges()
                    loadimages()
                End If
            Catch ex As Exception
                CheckForSQLErrors(ex)
            End Try
        End If
    End Sub

    Private Sub loadimages()
        Dim xImages = From imageList In dbItems.akaImages _
                                  Where imageList.AssetNo = textboxAssetNumber.Text

        ListBoxItemImages.DataContext = xImages
        ListBoxItemImages.SelectedIndex = 0
    End Sub

    Private Sub btnAddImage_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddImage.Click
        ofdImage.FileName = ""
        ofdImage.Filter = "Image Files|*.gif;*.jpg;*.bmp;*.png"
        ofdImage.Title = "Select Image"
        If ofdImage.ShowDialog() = System.Windows.Forms.DialogResult.Cancel Then
            Return
        Else
            Try
                If ofdImage.CheckFileExists() Then
                    Dim newImage As New akaImage
                    With newImage
                        .AssetNo = textboxAssetNumber.Text
                        .ImageLocation = ofdImage.FileName
                        .ImageName = ofdImage.SafeFileName
                    End With
                    dbItems.akaImages.InsertOnSubmit(newImage)
                    dbItems.SubmitChanges()
                    loadimages()
                Else
                    Dim warningString As String = "File does not exitst " & ControlChars.Lf & ofdImage.FileName
                    System.Windows.MessageBox.Show(warningString, "Error", MessageBoxButton.OK, MessageBoxImage.Warning)
                End If


            Catch ex As Exception

            End Try
        End If
    End Sub


    Private Sub listBoxItems_SelectionChanged1(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles listBoxItems.SelectionChanged
        Dim selectedItem As String = ""
        If Not listBoxItems.SelectedItem Is Nothing Then
            selectedItem = listBoxItems.SelectedValue.itemDetails.Assetno.ToString
        End If
        LoadSelectedItems(selectedItem)
    End Sub
End Class


